package com.xyy.yueshijia.myutil;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by wanggang on 2017/1/3.
 */

public class MyHttpUtils {
    //测试服务器
    //线上服务器
    private static final String BASE_URL = "BaseUrl :http://interface.yueshichina.com/";

    private static MyHttpUtils instance;
    private OkHttpClient client;
    private Handler handler;

    public static MyHttpUtils getInstance() {
        if (instance == null) {
            synchronized (MyHttpUtils.class) {
                if (instance == null) {
                    instance = new MyHttpUtils();
                }
            }
        }
        return instance;
    }

    //执行一次
    //初始化的操作
    private MyHttpUtils() {
        RewriteCacheControlInterceptor cacheInterceptor=new com.xyy.yueshijia.myutil.RewriteCacheControlInterceptor();
        //Log拦截器
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("=============", message);
            }
        });
        //设置拦截器Log等级
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //缓存路径   get请求   Cache-Control
        File cacheFile = FileUtils.getHttpCacheFile();

        Cache cache = new Cache(cacheFile, 1024 * 1024 * 10);


        //初始化OkhttpClient
        client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)//连接超时时间 与服务建立连接的时间
                .writeTimeout(20, TimeUnit.SECONDS)//发送数据超时时间
                .readTimeout(20, TimeUnit.SECONDS)//接收数据超时时间
                .addNetworkInterceptor(cacheInterceptor) //网络拦截器
                .addInterceptor(interceptor)//Log拦截器   response  intputstraem  只能读一次
                .cache(cache)//配置缓存路径
                .build();

        //保证回调在主线程执行
        //Looper 在哪个线程
        //Handler handleMessage 就在哪儿线程执行
        //Looper.getMainLooper()  保证handleMessage在主线程执行
        handler = new Handler(Looper.getMainLooper());
    }

    public void get(String path0,String path, HashMap<String, String> params, final HttpResponse callback) {

        //url 地址拼接
        StringBuilder url = new StringBuilder();
        url.append(path0);
      url.append(path);
       url.append("?");
        if (params != null && !params.isEmpty()) {

            Set<Map.Entry<String, String>> entries = params.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                url.append(entry.getKey());
                url.append("=");
                url.append(entry.getValue());
                url.append("&");
            }
        }
        url.setLength(url.length() - 1);
             Log.e("====url","url===="+url);
        //发起请求
        Request request = new Request.Builder()
                .url(url.toString())
//                .addHeader("Connection", "Keep-Alive")//保存长连接，减少Http握手消耗的时间
//                .addHeader("Accept-Encoding", "gzip")//对数据进行压缩
                .build();

        //下载  同步
        //普通请求  异步
        client.newCall(request).enqueue(new Callback() {
            //失败
            @Override
            public void onFailure(Call call, final IOException e) {
                if (callback != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(e.getMessage());
                        }
                    });
                }
            }

            //相应
            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                if (callback == null) return;
                if (response.isSuccessful()) {
                    //放工作线程支持  网络操作   读流
                    final String data = response.body().string();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            //成功
                            callback.onResponse(data);
                        }
                    });
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            //失败
                            callback.onError(response.message());
                        }
                    });
                }
            }
        });
    }
  //  public static HashMap<String, String> getBasicParams() {
    //    HashMap<String, String> basic = new HashMap<>();
    //    basic.put("osType", NetConfig.osType);
    //    basic.put("channel_from", NetConfig.channel_from);
    //    basic.put("source", NetConfig.source);
    //    basic.put("version", NetConfig.version);
     //   basic.put("appType", NetConfig.appType);

    //    return basic;
  //  }



    //拦截器
    //.addNetworkInterceptor() //网络拦截器
//    .addInterceptor(new Interceptor() {//Application 拦截器  拦截请求
//        @Override
//        public Response intercept(Interceptor.Chain chain) throws IOException {
//            //拦截请求
//            Request request = chain.request();
//            //添加公共参数
//            //打印日志
//
//            //执行网络请求
//            Response response = chain.proceed(request);
//
//            String string = response.body().string();
//
//            //status
//            //统一作处理
//
//            return null;
//        }
//    })


}
